<?php

namespace app\api\controller\balance;

use think\Db;
use think\Log;

class Withdraw
{

	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config  = [
		"log" 		=> "balance_log",
		"draw" 		=> "withdrawal_order"
	];

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}


	/**
	 * 查看 - 订单
	 */
	public function check_log_order($uid, $id)
	{
		if (!empty($uid) && !empty($id)) {
			$where = "main_id = {$uid} and balance_type_id = 7 and product_id = {$id}";
			$check = Db::name($this->config["log"])
				->where($where)
				->count();
			if (!$check) return true;
		}
		return false;
	}

	/**
	 * 余额 - 变更日志存储
	 */
	public function changs_balance_cords($orderno)
	{
		try {
			if (!empty($orderno) && is_string($orderno)) {
				$find = Db::name($this->config["draw"])
					->where("order_number = '{$orderno}'")
					->field("id,sale_id uid,withdrawal_money money,`before` orig,`after` aft")
					->find();
				// $find = ["id" => 123, "uid" => 12, "money" => 100, "orig" => 239, "aft" => 644];
				if ($find) {
					$option = [
						"uid"		=> $find["uid"], // 收入 或 支出 代理ID
						"typs"		=> 7, // 变更类型 1=分润,2=达标,3=流量卡,4=借款,5=还款,6=赠送,7=提现,8=认购 。。。。。。
						"isChg" 	=> 2, // 1 收入 2 支出
						"remark" 	=> "余额提现",	// 备注  => 没有备注传空字符串
						"orig"		=> $find["orig"], // 原余额    => 默认传0
						"chgAmt" 	=> $find["money"],	// 变更金额
						"after"		=> $find["aft"],  // 变更后余额
						"ids" 		=> $find["id"],	// 操作订单主ID | 分润、达标、流量卡、调价 传入产品ID
					];
					$checkLog = $this->check_log_order($option["uid"], $option["ids"]);
					if ($checkLog) {
						\app\common\controller\Balance::instance()->cords($option);
					}
				}
			}
		} catch (\Exception $e) {
			Log::write($e->getMessage());
		}
	}
}
